package com.fyy.netty.chapter01.c1;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * @Author fyy
 * @Description
 * @Date 2021/4/21 10:05
 */
public class FileChannelTransferTo {


    public static void fileChannelTransferTo(String readPath,String writePath) throws IOException {
        try (FileChannel readChannel = new FileInputStream(readPath).getChannel();
             FileChannel writeChannel = new FileOutputStream(writePath).getChannel()) {
            //效率高，底层使用零拷贝技术，最大支持2G文件传输
            readChannel.transferTo(0,readChannel.size(),writeChannel);

            //大于2G的文件可以多次传输
            long size = readChannel.size();
            for (long left = size; left > 0; ) {
                left -= readChannel.transferTo((size -left),left,writeChannel);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        String readPath = "F:\\test.txt";
        String writePath = "F:\\test2.txt";
        fileChannelTransferTo(readPath,writePath);
    }

}
